package de.ff7rl.core.reference;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;

import com.thoughtworks.xstream.XStream;

public abstract class WeakReference {

  private static final XStream XSTREAM = new XStream();
  private static final Map<String, Object> cache = new HashMap<String, Object>();

  public static <T> T getValue(final String thePath, final String theName, final String theExtension) {
    final String key = key(thePath, theName, theExtension);
    Object value = cache.get(key);
    if (value == null) {
      final InputStream inputStream = ClassLoader.getSystemResourceAsStream(FilenameUtils.concat("de/ff7rl/core/",
          FilenameUtils.concat(thePath, toFileName(theName) + theExtension)));
      if (inputStream == null) {
        throw new IllegalArgumentException(String.format("Unable to get referenced object %s%s from %s.", theName,
            theExtension, thePath));
      }
      value = XSTREAM.fromXML(inputStream);
      cache.put(key, value);
    }
    return (T) value;
  }

  public static String toFileName(final String theName) {
    return theName.replaceAll(" ", "_");
  }

  private static String key(final String thePath, final String theName, final String theExtension) {
    return String.format("%s.%s.%s", thePath, theName, theExtension);
  }

}
